<template>
  <div class="sms-mass-messaging-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="title-section">
        <h2 class="page-title">消息群发</h2>
        <el-tag type="success" effect="plain" class="version-tag">企业版</el-tag>
      </div>

    </div>

    <!-- 信息提示条 -->
    <el-alert
      title="消息群发功能支持定时发送和批量导入号码，发送前请确保消息内容合规，避免被判定为垃圾消息。"
      type="info"
      show-icon
      :closable="false"
      class="info-alert"
    />

    <!-- 主要内容区域 -->
    <el-row :gutter="20">
      <!-- 左侧：消息编辑区域 -->
      <el-col :xs="24" :sm="24" :md="16" :lg="16">
        <el-card shadow="hover" class="message-editor-card">
          <div slot="header" class="card-header">
            <div class="header-title">
              <i class="el-icon-edit-outline"></i>
              <span>消息内容</span>
            </div>
            <div class="header-actions">
              <el-button type="text" icon="el-icon-delete" @click="clearMessage">清空</el-button>
            </div>
          </div>

          <!-- 消息类型选择 -->
          <el-form :model="messageForm" :rules="formRules" ref="messageForm" label-width="100px">
            <el-form-item label="消息类型" prop="templateType">
              <el-radio-group v-model="messageForm.templateType">
                <el-radio label="1">通知消息</el-radio>
                <el-radio label="2">营销消息</el-radio>
                <el-radio label="3">智能消息</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 消息签名 -->
            <el-form-item label="消息签名" prop="signatureName">
              <el-select v-model="messageForm.signatureId" style="width: 100%;" filterable placeholder="请选择关联签名" clearable @change="handleSignatureChange">
                <el-option v-for="item in signatures" :key="item.signatureId" :label="item.signatureName" :value="item.signatureId"></el-option>
              </el-select>
            </el-form-item>

            <!-- 消息模版 -->
            <el-form-item label="消息模版" prop="templateId">
              <div class="template-selector">
                <el-select
                  v-model="messageForm.templateId"
                  placeholder="请选择消息模版"
                  style="width: calc(100% - 110px)"
                  @change="handleTemplateChange"
                >
                  <el-option
                    v-for="item in currentTemplates"
                    :key="item.templateId"
                    :label="item.templateName"
                    :value="item.templateId"
                  >
                    <div class="template-option">
                      <div class="template-name">{{ item.templateName }}</div>
                      <div class="template-content">{{ item.templateContent }}</div>
                    </div>
                  </el-option>
                </el-select>
                <el-button type="primary" size="small" @click="showTemplateDialog">选择模版</el-button>
              </div>
            </el-form-item>

            <!-- 任务名称 -->
            <el-form-item label="任务名称" prop="taskName">
              <el-input
                v-model="messageForm.taskName"
                placeholder="请输入任务名称，不填写将自动生成"
                clearable
              ></el-input>
            </el-form-item>

            <!-- 消息内容 -->
            <el-form-item label="消息内容" prop="templateContent">
              <el-input
                type="textarea"
                v-model="messageForm.templateContent"
                :rows="6"
                placeholder="请输入消息内容，营销消息请在内容结尾添加退订方式"
                @input="updateCharCount"
              ></el-input>
<!--              <div class="content-footer">-->
<!--                <div class="variable-buttons" v-if="messageForm.messageType !== 'marketing'">-->
<!--                  <el-button type="text" size="small" @click="insertVariable('name')">插入姓名变量</el-button>-->
<!--                  <el-button type="text" size="small" @click="insertVariable('code')">插入验证码变量</el-button>-->
<!--                  <el-button type="text" size="small" @click="insertVariable('date')">插入日期变量</el-button>-->
<!--                </div>-->
<!--                <div class="char-counter" :class="{ 'warning': charCount > 400 }">-->
<!--                  <span>{{ charCount }}/500字符</span>-->
<!--                  <span class="message-count">({{ messageCount }}条消息)</span>-->
<!--                </div>-->
<!--              </div>-->
            </el-form-item>

            <!-- 接收人设置 -->
            <el-form-item label="接收人" prop="recipientType">
              <el-radio-group v-model="messageForm.recipientType" @change="handleRecipientTypeChange">
                <el-radio label="group">选择分组</el-radio>
                <el-radio label="upload">导入号码</el-radio>
                <el-radio label="manual">手动输入</el-radio>
              </el-radio-group>

              <!-- 分组选择 -->
              <div v-if="messageForm.recipientType === 'group'">
                <el-button type="primary" @click="showContactDialog">选择联系人</el-button>
                <div v-if="selectedContacts.length > 0" class="selected-contacts-preview">
                  <el-tag
                    v-for="contact in selectedContacts.slice(0, 5)"
                    :key="contact.customerId"
                    type="info"
                    size="small"
                    style="margin: 2px;"
                  >{{ contact.customerName }}</el-tag>
                  <span v-if="selectedContacts.length > 5" class="more-contacts">
                    等{{ selectedContacts.length }}个联系人
                  </span>
                </div>
              </div>

              <!-- 导入号码 -->
              <div v-if="messageForm.recipientType === 'upload'" class="recipient-upload">
                <el-upload
                  class="upload-demo"
                  action="#"
                  :http-request="handleFileUpload"
                  :on-change="handleFileChange"
                  :on-remove="handleFileRemove"
                  :file-list="fileList"
                  :auto-upload="true"
                  :limit="1"
                  accept=".xls,.xlsx"
                  :before-upload="beforeExcelUpload"
                >
                  <el-button size="small" type="primary">选择文件</el-button>
                  <div slot="tip" class="el-upload__tip">
                    1、文件需小于50M，Excel文件有效号码需少于100万；
                    2、文件支持xls、xlsx格式。
                    <el-button type="text" size="small" icon="el-icon-download" @click.stop="downloadPhoneTemplate">下载模版</el-button>
                  </div>
                </el-upload>

                <!-- 联系人列表 -->
                <div v-if="uploadedPhones.length > 0" class="contacts-preview">
                  <div class="contacts-header">
                    <span class="contact-count">已导入 <span class="highlight">{{ uploadedPhones.length }}</span> 个联系人</span>
                    <div class="contacts-actions">
                      <!-- <el-button type="text" size="small" @click="showContactsDialog">查看全部</el-button>
                      <el-button type="text" size="small" @click="clearAllContacts">清空</el-button> -->
                    </div>
                  </div>

                  <!-- 联系人列表操作栏 -->
                  <div class="contacts-toolbar">
                    <div class="left-tools">
                      <el-button
                        size="small"
                        type="danger"
                        :disabled="selectedContacts.length === 0"
                        @click="deleteSelectedContacts"
                      >批量删除</el-button>
                      <el-button
                        size="small"
                        type="primary"
                        @click="addNewContact"
                      >添加联系人</el-button>
                    </div>
                    <div class="right-tools">
                      <el-input
                        placeholder="搜索联系人"
                        v-model="contactSearchQuery"
                        prefix-icon="el-icon-search"
                        size="small"
                        style="width: 200px;"
                      ></el-input>
                      <el-select v-model="pageSize" size="small" placeholder="每页显示" style="width: 120px; margin-left: 10px;">
                        <el-option
                          v-for="item in [500, 1000, 5000]"
                          :key="item"
                          :label="`${item}条/页`"
                          :value="item">
                        </el-option>
                      </el-select>
                    </div>
                  </div>

                  <!-- 联系人表格 -->
                  <el-table
                    :data="paginatedContacts"
                    style="width: 100%"
                    max-height="400"
                    border
                    size="small"
                    @selection-change="handleContactSelectionChange"
                  >
                    <el-table-column
                      type="selection"
                      width="50"
                      align="center"
                    ></el-table-column>
                    <el-table-column
                      type="index"
                      width="50"
                      label="序号"
                      align="center"
                    ></el-table-column>
                    <el-table-column
                      prop="phone"
                      label="手机号码"
                      width="140"
                    >
                      <template slot-scope="scope">
                        <el-input v-if="scope.row.editing" v-model="scope.row.phone" size="small"></el-input>
                        <span v-else>{{ scope.row.phone }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="变量1" prop="variable1" width="120">
                      <template slot-scope="scope">
                        <el-input v-if="scope.row.editing" v-model="scope.row.variable1" size="small"></el-input>
                        <span v-else>{{ scope.row.variable1 }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="变量2" prop="variable2" width="120">
                      <template slot-scope="scope">
                        <el-input v-if="scope.row.editing" v-model="scope.row.variable2" size="small"></el-input>
                        <span v-else>{{ scope.row.variable2 }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="变量3" prop="variable3" width="120">
                      <template slot-scope="scope">
                        <el-input v-if="scope.row.editing" v-model="scope.row.variable3" size="small"></el-input>
                        <span v-else>{{ scope.row.variable3 }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="变量4" prop="variable4" >
                      <template slot-scope="scope">
                        <el-input v-if="scope.row.editing" v-model="scope.row.variable4" size="small"></el-input>
                        <span v-else>{{ scope.row.variable4 }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="操作"
                      width="150"
                      align="center"
                    >
                      <template slot-scope="scope">
                        <div v-if="scope.row.editing">
                          <el-button type="text" size="small" @click="saveContact(scope.row)">保存</el-button>
                          <el-button type="text" size="small" @click="cancelEdit(scope.row, scope.$index)">取消</el-button>
                        </div>
                        <div v-else>
                          <el-button type="text" size="small" @click="editContact(scope.row)">编辑</el-button>
                          <el-button type="text" size="small" @click="deleteContact(scope.$index)">删除</el-button>
                        </div>
                      </template>
                    </el-table-column>
                  </el-table>

                  <!-- 分页控件 -->
                  <div class="pagination-container">
                    <el-pagination
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                      :current-page="currentPage"
                      :page-sizes="[500, 1000, 5000]"
                      :page-size="pageSize"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="filteredContacts.length">
                    </el-pagination>
                  </div>
                </div>
              </div>

              <!-- 手动输入 -->
              <div v-if="messageForm.recipientType === 'manual'" class="recipient-manual">
                <el-input
                  type="textarea"
                  v-model="messageForm.manualRecipients"
                  :rows="6"
                  placeholder="请输入手机号码，多个号码请用逗号、空格或换行分隔"
                  @input="validateManualRecipients"
                  ref="manualInput"
                ></el-input>
                <div class="manual-recipient-counter">
                  已输入 <span class="highlight">{{ manualRecipientCount }}</span> 个有效号码
                </div>
                <div v-if="messageForm.manualRecipients && manualRecipientCount === 0" class="manual-error-tip">
                  <i class="el-icon-warning"></i>
                  未检测到有效的手机号码，请确保格式正确（11位手机号）
                </div>
              </div>
            </el-form-item>

            <!-- 定时发送 -->
            <el-form-item label="定时发送" prop="scheduledTime">
              <div class="schedule-selector">
                <el-date-picker
                  v-model="messageForm.scheduledTime"
                  type="datetime"
                  placeholder="请选择发送时间"
                  format="yyyy-MM-dd HH:mm"
                  value-format="yyyy-MM-dd HH:mm"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧：预览和统计 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8">
        <!-- 发送统计 -->
        <el-card shadow="hover" class="stats-card">
          <div slot="header" class="card-header">
            <div class="header-title">
              <i class="el-icon-data-analysis"></i>
              <span>发送统计</span>
            </div>
          </div>

          <div class="stats-content">
            <div class="stats-item">
              <div class="stats-label">接收人数</div>
              <div class="stats-value">{{ recipientCount }}</div>
            </div>
            <div class="stats-item">
              <div class="stats-label">消息条数</div>
              <div class="stats-value">{{ totalMessageCount }}</div>
            </div>
            <div class="stats-item">
              <div class="stats-label">每条价格</div>
              <div class="stats-value price">¥ {{ unitPrice.toFixed(3) }}</div>
            </div>
            <div class="stats-item">
              <div class="stats-label">预计费用</div>
              <div class="stats-value price highlight">¥ {{ estimatedCost.toFixed(2) }}</div>
            </div>
          </div>
          <div class="header-actions">
            <el-button type="primary" icon="el-icon-s-promotion" @click="handleSendMessage" :disabled="!canSend">
              定时发送
            </el-button>
            <el-button type="primary" icon="el-icon-folder" @click="handleSaveDraft" :disabled="!canSaveDraft">
              暂存任务
            </el-button>
          </div>
        </el-card>
        <!-- 消息预览 -->
        <el-card shadow="hover" class="preview-card">
          <div slot="header" class="card-header">
            <div class="header-title">
              <i class="el-icon-mobile-phone"></i>
              <span>消息预览</span>
            </div>
            <div class="header-actions">
              <el-button type="text" icon="el-icon-refresh" @click="refreshPreview">刷新</el-button>
            </div>
          </div>

          <div class="phone-preview">
            <div class="phone-frame">
              <div class="phone-header">
                <div class="phone-time">{{ currentTime }}</div>
              </div>
              <div class="phone-content">
                <div class="message-bubble">
                  <div class="message-sender">{{ getSignatureName }}</div>
                  <div class="message-content">{{ previewContent }}</div>
                  <div class="message-time">{{ currentTime }}</div>
                </div>
              </div>
            </div>
          </div>
        </el-card>



        <!-- 发送记录 -->
        <el-card shadow="hover" class="history-card">
          <div slot="header" class="card-header">
            <div class="header-title">
              <i class="el-icon-time"></i>
              <span>最近发送记录</span>
            </div>
            <div class="header-actions">
              <el-button type="text" @click="viewAllHistory">查看全部</el-button>
            </div>
          </div>

          <div class="history-list">
            <el-table
              :data="sendHistory"
              style="width: 100%"
              :show-header="false"
              size="small"
            >
              <el-table-column width="80">
                <template slot-scope="scope">
                  <el-tag
                    size="mini"
                    :type="getTaskStatusType(scope.row.taskStatus)"
                  >{{ getTaskStatusText(scope.row.taskStatus) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column>
                <template slot-scope="scope">
                  <div class="history-item">
                    <div class="history-title">{{ scope.row.taskName }}</div>
                    <div class="history-info">
                      <span>{{ scope.row.createTime }}</span>
                      <span>{{ scope.row.totalRecipients }}人</span>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column width="60">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" @click="loadTaskData(scope.row)">选择</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 模版管理对话框 -->
    <el-dialog
      :title="getTemplateDialogTitle()"
      :visible.sync="templateDialogVisible"
      width="1200px"
      :class="messageForm.templateType === '3' ? 'smart-template-dialog' : 'normal-template-dialog'"
    >
      <div class="template-dialog-content">
        <div class="template-actions">
          <el-input
            placeholder="搜索模版"
            v-model="templateSearchQuery"
            prefix-icon="el-icon-search"
            size="small"
            style="width: 200px; margin-left: auto;"
          ></el-input>
        </div>

        <!-- 智能消息模版 - 卡片模式 -->
        <div v-if="messageForm.templateType === '3'" class="smart-templates-container">
          <div v-if="filteredSmartTemplates.length > 0" class="template-cards">
            <div
              v-for="item in filteredSmartTemplates"
              :key="item.templateId"
              class="template-card"
              @click="handleUseTemplate(item)"
            >
              <div class="card-status">
                <el-tag size="mini" type="success">已通过</el-tag>
              </div>

              <div class="card-image">
                <el-image
                  v-if="item.imgUrl"
                  :src="item.imgUrl"
                  fit="cover"
                  style="width: 100%; height: 120px;"
                />
                <div v-else class="no-image">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </div>

              <div class="card-info">
                <h4 class="card-title">{{ item.templateName }}</h4>
                <p class="card-description">{{ item.templateContent }}</p>
                <div class="card-meta">
                  <span>ID: {{ item.templateId }}</span>
                  <span v-if="item.signatureName">签名: {{ item.signatureName }}</span>
                </div>
              </div>

              <div class="card-footer">
                <el-button type="primary" size="mini" @click.stop="handleUseTemplate(item)">
                  使用模版
                </el-button>
              </div>
            </div>
          </div>

          <!-- 智能模版空状态 -->
          <div v-else class="empty-state">
            <i class="el-icon-document-copy"></i>
            <p>{{ templateSearchQuery ? '未找到匹配的智能模版' : '暂无已通过的智能模版' }}</p>
          </div>

          <!-- 智能模版分页 -->
          <div class="template-pagination" v-if="smartTemplateTotal > 0">
            <el-pagination
              @current-change="handleSmartTemplatePageChange"
              :current-page="smartTemplateParams.pageNum"
              :page-size="smartTemplateParams.pageSize"
              layout="prev, pager, next"
              :total="smartTemplateTotal">
            </el-pagination>
          </div>
        </div>

        <!-- 通知消息模版 - 表格模式 -->
        <div v-else class="normal-templates-container">
          <el-table
            v-if="normalTemplates.length > 0"
            :data="normalTemplates"
            style="width: 100%"
            :header-cell-style="tableHeaderStyle"
            border
            class="custom-table"
            @row-dblclick="handleUseTemplate"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="模版ID" align="center" prop="templateId" width="140" />
            <el-table-column label="模版名称" prop="templateName" min-width="120" show-overflow-tooltip></el-table-column>
            <el-table-column label="签名名称" align="center" prop="signatureName" min-width="80" :show-overflow-tooltip="true" />
            <el-table-column label="模版内容" prop="templateContent" min-width="250" show-overflow-tooltip></el-table-column>
            <el-table-column label="模版类型" prop="templateType" width="90" align="center">
                      <template slot-scope="scope">
          {{ scope.row.templateType == 1 ? '普通短信' : scope.row.templateType == 2 ? '智能短信' : scope.row.templateType }}
        </template>
            </el-table-column>
            <el-table-column label="审核状态" prop="auditStatus" width="90" align="center">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.audit_status" :value="scope.row.auditStatus"/>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleUseTemplate(scope.row)">使用</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 通知模版空状态 -->
          <div v-else class="empty-state">
            <i class="el-icon-document"></i>
            <p>{{ getEmptyStateMessage() }}</p>
          </div>
        </div>
      </div>
    </el-dialog>


    <!-- 发送确认对话框 -->
    <el-dialog
      title="发送确认"
      :visible.sync="sendConfirmDialogVisible"
      width="500px"
    >
      <div class="send-confirm-content">
        <div class="confirm-icon">
          <i class="el-icon-warning"></i>
        </div>
        <div class="confirm-info">
          <p class="confirm-title">您确定要发送此消息吗？</p>
          <p class="confirm-detail">接收人数：<span class="highlight">{{ recipientCount }}</span> 人</p>
          <p class="confirm-detail">消息条数：<span class="highlight">{{ totalMessageCount }}</span> 条</p>
          <p class="confirm-detail">每条价格：<span class="highlight">¥ {{ unitPrice.toFixed(3) }}</span></p>
          <p class="confirm-detail">预计费用：<span class="highlight">¥ {{ estimatedCost.toFixed(2) }}</span></p>
          <p v-if="messageForm.scheduledSend" class="confirm-detail">发送时间：{{ messageForm.scheduledTime }}</p>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="sendConfirmDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSendMessage">确认发送</el-button>
      </div>
    </el-dialog>

    <!-- 联系人选择对话框 -->
    <el-dialog title="选择联系人" :visible.sync="contactDialogVisible" width="1200px" append-to-body>
      <el-row :gutter="20">
        <!-- 左侧：客户分组树 -->
        <el-col :span="6">
          <el-card shadow="never" class="group-tree-card">
            <div slot="header" class="card-header">
              <span>客户分组</span>
            </div>
            <el-tree
              :data="contactGroupTreeData"
              :props="contactTreeProps"
              node-key="groupId"
              default-expand-all
              highlight-current
              @node-click="handleContactGroupClick"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span class="node-label">
                  <i v-if="data.groupId == 0" class="el-icon-s-home tree-icon" />
                  <i v-else class="el-icon-folder tree-icon" />
                  {{ data.groupName }}
                </span>
              </span>
            </el-tree>
          </el-card>
        </el-col>

        <!-- 右侧：客户列表 -->
        <el-col :span="18">
          <el-card shadow="never" class="contact-list-card">
            <div slot="header" class="card-header">
              <span>{{ currentContactGroupName }}</span>
              <div>
                <el-input
                  v-model="contactQueryParams.customerName"
                  placeholder="搜索客户姓名"
                  clearable
                  size="small"
                  style="width: 200px; margin-right: 10px"
                  @keyup.enter.native="getContactList"
                />
                <el-button type="primary" size="small" @click="getContactList">搜索</el-button>
              </div>
            </div>

            <el-table
              ref="contactTable"
              v-loading="contactLoading"
              :data="contactList"
              @selection-change="handleContactSelectionChange"
              height="400px"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="客户姓名" prop="customerName" width="120" />
              <el-table-column label="手机号码" prop="phoneNumber" min-width="140" />
              <el-table-column label="客户分组" prop="groupName" width="120" />
              <el-table-column label="创建时间" prop="createTime" width="160">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="contactTotal > 0"
              :total="contactTotal"
              :page.sync="contactQueryParams.pageNum"
              :limit.sync="contactQueryParams.pageSize"
              @pagination="getContactList"
            />
          </el-card>
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <span style="float: left; line-height: 32px;">
          已选择 <span style="color: #409EFF; font-weight: bold;">{{ selectedContacts.length }}</span> 个联系人
        </span>
        <el-button @click="contactDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmContactSelection">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {listTemplate, updateTemplate} from "@/api/Sms/template";
import {listSmsTemplateMms} from "@/api/Sms/SmsTemplateMms";
import {listSignatures} from "@/api/Sms/signatures";
import {listVariable} from "@/api/Sms/variable";
import {addBulkTask, updateBulkTask, sendBulkTask, listBulkTask, getBulkTask} from "@/api/Sms/bulktask";
import * as XLSX from 'xlsx';
import {getPriceByUserId} from "@/api/Sms/SmsRecord";
import {
  listContactGroup,
  treeSelectContactGroup
} from "@/api/Sms/contactGroup";
import {
  listContactCustomer
} from "@/api/Sms/contactCustomer";


export default {
  name: 'SmsMassMessaging',
  components: { },
  dicts: ["audit_status"],
  data() {
    return {
      // 消息表单
      messageForm: {
        templateType: '1',
        signatureId: '',
        signatureName: '',
        templateId: '',
        templateName: '',
        templateContent: '',
        taskName: '',
        recipientType: 'group',
        recipientGroup: '',
        manualRecipients: '', // Ensure this field is initialized
        scheduledTime: ''
      },

      // 表单验证规则
      formRules: {
        templateType: [
          { required: true, message: '请选择消息类型', trigger: 'change' }
        ],
        signatureName: [
          { required: true, message: '请选择消息签名', trigger: 'change' }
        ],
        templateId: [
          { required: true, message: '请选择消息模版', trigger: 'change' }
        ],
        taskName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        templateContent: [
          { required: true, message: '请输入消息内容', trigger: 'blur' }
        ],
        recipientType: [
          { required: true, message: '请选择接收人类型', trigger: 'change' },
          { validator: this.validateRecipients, trigger: 'change' }
        ],
        scheduledTime: [
          { required: true, message: '请选择发送时间', trigger: 'change' }
        ]
      },

      // 消息签名列表
      signatures: [
      ],

      // 消息模版列表
      normalTemplates: [
      ],
      // 智能消息模版列表
      smartTemplates: [
      ],
      //消息变量列表
      variables: [
      ],


      // 文件上传
      fileList: [],
      uploadedPhones: [],

      // 手动输入的接收人
      manualRecipientCount: 0,

      // 字符计数
      charCount: 0,
      messageCount: 1,

      // 发送历史
      sendHistory: [

      ],

      // 对话框
      templateDialogVisible: false,
      templateEditDialogVisible: false,
      sendConfirmDialogVisible: false,
      contactsDialogVisible: false,
      contactDialogVisible: false,

      // 模版搜索
      templateSearchQuery: '',

      // 智能模版分页参数
      smartTemplateParams: {
        pageNum: 1,
        pageSize: 12
      },
      smartTemplateTotal: 0,

      // 模版编辑
      templateEditMode: 'add',
      templateForm: {
        id: '',
        name: '',
        content: '',
        type: 'notification'
      },
      // 价格信息
      priceInfo: {
        smsNoticePrice: 0.080,
        smsSellPrice: 0.085,
        smsPicturePrice: 0.090,
        smsVoicePrice: 0.100,
        smsSmartPrice: 0.120
      },
      // 模版表单验证规则
      templateRules: {
        name: [
          { required: true, message: '请输入模版名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择模版类型', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入模版内容', trigger: 'blur' }
        ]
      },

      // 日期选择器配置
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
        }
      },


      // 联系人列表相关
      contactSearchQuery: '',
      currentPage: 1,
      pageSize: 500,
      selectedContacts: [],
      newVariableKey: '',
      newVariableValue: '',

      // 联系人选择相关
      contactGroupTreeData: [],
      contactTreeProps: {
        children: 'children',
        label: 'groupName'
      },
      currentContactGroupId: null,
      currentContactGroupName: '全部联系人',
      contactList: [],
      contactLoading: false,
      contactTotal: 0,
      contactQueryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
        groupId: null
      },
    }
  },
  created() {
    this.getPriceInfo();
    this.getTemplateList();
    this.getSignaturesList();
    this.getVariableList();
    this.getHistorySmsTask();

    this.getContactGroupTree();

    // 设置定时发送默认值为当前时间后10分钟
    this.setDefaultScheduledTime();
  },
  computed: {
    // 当前时间
    currentTime() {
      const now = new Date();
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },

    // 获取签名名称
    getSignatureName() {
      const signature = this.signatures.find(sig => sig.signatureId === this.messageForm.signatureId);
      return signature ? `【${signature.signatureName}】` : '';
    },

    // 预览内容
    previewContent() {
      let content = this.getSignatureName + this.messageForm.templateContent;

      // 替换变量
      content = content.replace(/\${name}/g, '张三');
      content = content.replace(/\${code}/g, '123456');
      content = content.replace(/\${date}/g, '2025-04-01');

      return content;
    },

    // 接收人数量
    recipientCount() {
      if (this.messageForm.recipientType === 'group') {
        return this.selectedContacts.length;
      } else if (this.messageForm.recipientType === 'upload') {
        return this.uploadedPhones.length;
      } else {
        return this.manualRecipientCount;
      }
    },

    // 总消息条数
    totalMessageCount() {
      return this.recipientCount * this.messageCount;
    },

    // 单条价格
    unitPrice() {
      ////console.log("hqdamja:")
      //console.log(this.$store.getters)

      // 根据消息类型获取对应价格
      if (this.messageForm.templateType === '1') {
        // 通知消息
        return parseFloat(this.priceInfo.smsNoticePrice || 0.080);
      } else if (this.messageForm.templateType === '2') {
        // 营销消息
        return parseFloat(this.priceInfo.smsSellPrice || 0.085);
      } else if (this.messageForm.templateType === '3') {
        // 智能消息模板
        return parseFloat(this.priceInfo.smsSmartPrice || 0.120);
      }
      // 默认价格
      return 0.080;
    },

    // 预计费用
    estimatedCost() {
      return this.totalMessageCount * this.unitPrice;
    },

    // 是否可以发送
    canSend() {
      return this.messageForm.templateContent &&
        this.messageForm.signatureId &&
        this.recipientCount > 0 &&
        this.messageForm.scheduledTime;
    },

    // 是否可以暂存
    canSaveDraft() {
      return this.messageForm.templateContent &&
        this.messageForm.signatureId &&
        this.recipientCount > 0;
    },

    // 过滤后的联系人列表
    filteredContacts() {
      if (!this.contactSearchQuery) {
        return this.uploadedPhones;
      }

      const query = this.contactSearchQuery.toLowerCase();
      console.log("sdsa"+query);
      return this.uploadedPhones.filter(contact =>
        contact.phone.toLowerCase().includes(query) ||
        contact.variable1.toLowerCase().includes(query) ||
        contact.variable2.toLowerCase().includes(query) ||
        contact.variable3.toLowerCase().includes(query) ||
        contact.variable4.toLowerCase().includes(query)
      );
    },

    // 分页后的联系人列表
    paginatedContacts() {
      return this.filteredContacts.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
    },

    // 根据消息类型获取对应的模板列表
    currentTemplates() {
      if (this.messageForm.templateType === '3') {
        // 智能消息模板
        return this.smartTemplates.map(template => ({
          templateId: template.tmId,
          templateName: template.tplName,
          templateContent: template.tplContent,
          templateType: '4',
          signatureId: template.signatureId,
          signatureName: template.signatureName
        }));
      } else {
        // 普通模板（通知和营销）
        return this.normalTemplates;
      }
    },

    // 过滤后的智能模版（只显示已通过的）
    filteredSmartTemplates() {
      const allSmartTemplates = this.smartTemplates
        .filter(template => template.auditState === 2) // 只显示已通过的
        .map(template => ({
          templateId: template.tmId,
          templateName: template.tplName,
          templateContent: template.tplContent,
          templateType: '4',
          signatureId: template.signatureId,
          signatureName: template.signatureName,
          imgUrl: template.imgUrl
        }));

      // 搜索过滤
      let filtered = allSmartTemplates;
      if (this.templateSearchQuery) {
        const query = this.templateSearchQuery.toLowerCase();
        filtered = allSmartTemplates.filter(template =>
          template.templateName.toLowerCase().includes(query) ||
          template.templateContent.toLowerCase().includes(query) ||
          template.templateId.toString().includes(query)
        );
      }

      // 分页处理
      this.smartTemplateTotal = filtered.length;
      const start = (this.smartTemplateParams.pageNum - 1) * this.smartTemplateParams.pageSize;
      const end = start + this.smartTemplateParams.pageSize;
      return filtered.slice(start, end);
    },

    // 过滤后的通知模版
    filteredNormalTemplates() {
      let filtered = this.normalTemplates.filter(template =>
        template.templateType === this.messageForm.templateType
      );

      // 搜索过滤
      if (this.templateSearchQuery) {
        const query = this.templateSearchQuery.toLowerCase();
        filtered = filtered.filter(template =>
          template.templateName.toLowerCase().includes(query) ||
          template.templateContent.toLowerCase().includes(query) ||
          template.templateId.toString().includes(query)
        );
      }

      return filtered;
    },
  },
  watch: {
    // 监听消息类型变化
    'messageForm.templateType'(newType, oldType) {
      if (newType !== oldType) {
        // 清空模板选择
        this.messageForm.templateId = '';
        this.messageForm.templateName = '';
        this.messageForm.templateContent = '';

        // 重置模版搜索和分页
        this.templateSearchQuery = '';
        this.smartTemplateParams.pageNum = 1;

        // 根据新的消息类型重新获取模板列表
        this.getTemplateList();

        console.log(`消息类型从 ${oldType} 切换到 ${newType}，已清空模板选择并重新获取模板列表`);
      }
    },

    // 监听模版搜索变化，重置分页
    templateSearchQuery() {
      this.smartTemplateParams.pageNum = 1;
    }
  },
  methods: {


    /** 获取价格信息 */
    async getPriceInfo() {
      try {
        const userId = this.$store.state.user.userId;
        console.log("正在获取价格信息，用户ID:", userId);

        const response = await getPriceByUserId(userId);
        console.log("价格信息接口响应:", response);

        if (response && response.code === 200 && response.data) {
          // 更新价格信息
          this.priceInfo = {
            smsNoticePrice: parseFloat(response.data.smsNoticePrice || 0.080),
            smsSellPrice: parseFloat(response.data.smsSellPrice || 0.085),
            smsPicturePrice: parseFloat(response.data.smsPicturePrice || 0.090),
            smsVoicePrice: parseFloat(response.data.smsVoicePrice || 0.100),
            smsSmartPrice: parseFloat(response.data.smsSmartPrice || 0.120)
          };
        } else {
          console.warn("价格信息接口返回数据格式异常:", response);
        }
      } catch (error) {
        console.error("获取价格信息失败:", error);
        // 使用默认价格
        console.log("使用默认价格信息:", this.priceInfo);
      }
    },

    /** 查询短信模板列表 */
    getTemplateList() {
      this.loading = true;
      listTemplate({pageSize: 1000, auditStatus: 'successful',userId :this.$store.state.user.userId, templateType: this.messageForm.templateType}).then(response => {
        this.normalTemplates = response.rows;
        this.total = response.total;
        this.loading = false;
      });

      // 同时获取智能模板列表
      this.getSmartTemplateList();
    },

    /** 查询智能模板列表 */
    getSmartTemplateList() {
      listSmsTemplateMms({pageSize: 1000, auditState: 2,userId :this.$store.state.user.userId}).then(response => {
        this.smartTemplates = response.rows || [];
        console.log("智能模板列表:", this.smartTemplates);
      }).catch(error => {
        console.error('获取智能模板失败:', error);
        this.smartTemplates = [];
      });
    },
    /** 获取签名列表 */
    getSignaturesList() {
      listSignatures({pageSize: 1000, auditStatus: 'successful',userId :this.$store.state.user.userId}).then(response => {
        this.signatures = response.rows;
      });
    },
    getHistorySmsTask()
    {

      listBulkTask({userId: this.$store.state.user.userId, pageSize: 5}).then(response => {
        this.sendHistory = response.rows;
      });
    },
    /** 处理签名变更 */
    handleSignatureChange(signatureId) {
      if (signatureId) {
        const selectedSignature = this.signatures.find(item => item.signatureId === signatureId);
        if (selectedSignature) {
          this.messageForm.signatureName = selectedSignature.signatureName;
        }
      } else {
        this.messageForm.signatureName = null;
      }
    },
    /** 获取模板变量列表 */
    getVariableList() {
      listVariable({pageSize: 1000}).then(response => {
        this.variables = response.rows;
      });
    },
    // 更新字符计数
    updateCharCount() {
      this.charCount = this.messageForm.templateContent ? this.messageForm.templateContent.length : 0;
      this.messageCount = Math.ceil(this.charCount / 70);

      // 如果没有设置任务名称，则自动生成
      if (!this.messageForm.taskName && this.messageForm.templateContent) {
        // 获取内容的前10个字符，如果有内容的话
        const contentPreview = this.messageForm.templateContent.substring(0, 10);
        // 生成任务名称，格式：日期_内容预览
        const date = new Date();
        const dateStr = `${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}${String(date.getDate()).padStart(2, '0')}`;
        this.messageForm.taskName = `${dateStr}_${contentPreview}${contentPreview.length < 10 ? '' : '...'}`;
      }
    },

    // 插入变量
    insertVariable(type) {
      const variables = {
        name: '${name}',
        code: '${code}',
        date: '${date}'
      };

      const variable = variables[type];
      if (!variable) return;

      const textarea = document.querySelector('textarea[name="content"]');
      if (textarea) {
        const start = textarea.selectionStart;
        const end = textarea.selectionEnd;

        this.messageForm.templateContent = this.messageForm.templateContent.substring(0, start) +
          variable +
          this.messageForm.templateContent.substring(end);

        this.$nextTick(() => {
          textarea.selectionStart = start + variable.length;
          textarea.selectionEnd = start + variable.length;
          textarea.focus();
        });
      } else {
        this.messageForm.templateContent += variable;
      }

      this.updateCharCount();
    },

    // 清空消息
    clearMessage() {
      this.$confirm('确定要清空当前编辑的消息内容吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 重置表单
        this.$refs.messageForm.resetFields();
        
        // 清空其他相关数据
        this.selectedContacts = [];
        this.uploadedPhones = [];
        this.fileList = [];
        this.manualRecipientCount = 0;
        
        // 清空联系人表格选择状态
        if (this.$refs.contactTable) {
          this.$refs.contactTable.clearSelection();
        }
        
        // 重新初始化定时发送时间
        this.setDefaultScheduledTime();
        
        this.updateCharCount();
        this.$message.success('已清空消息内容');
      }).catch(() => {});
    },

    // 处理模板变更
    handleTemplateChange(templateId) {
      console.log("选择模板ID:", templateId);

      // 从当前模板列表中查找模板
      const template = this.currentTemplates.find(t => t.templateId === templateId);
      if (template) {
        console.log("找到模板:", template);

        // 将 templateType 转换为字符串，确保 radio-group 能正确选中
        this.messageForm.templateType = String(template.templateType);
        this.messageForm.templateName = template.templateName;
        this.messageForm.templateContent = template.templateContent;

        // 处理签名信息
        if (template.signatureId) {
          this.messageForm.signatureId = template.signatureId;
          this.messageForm.signatureName = template.signatureName;
        }

        // 生成任务名称
        if (!this.messageForm.taskName) {
          const date = new Date();
          const dateStr = `${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}${String(date.getDate()).padStart(2, '0')}`;
          this.messageForm.taskName = `${dateStr}_${template.templateName}`;
        }

        this.updateCharCount();
        console.log("更新后的表单:", this.messageForm);
      } else {
        console.warn("未找到模板:", templateId);
      }
    },

    // 处理接收人类型变更
    handleRecipientTypeChange() {
      console.log('接收人类型变更:', this.messageForm.recipientType);

      // 重置相关字段
      if (this.messageForm.recipientType === 'group') {
        this.selectedContacts = [];
        this.uploadedPhones = [];
        this.messageForm.manualRecipients = '';
        this.manualRecipientCount = 0;
      } else if (this.messageForm.recipientType === 'upload') {
        this.fileList = [];
        this.uploadedPhones = [];
        this.selectedContacts = [];
        this.messageForm.manualRecipients = ''; // 清空手动输入
      } else if (this.messageForm.recipientType === 'manual') {
        this.fileList = [];
        this.selectedContacts = [];
        this.uploadedPhones = [];
        this.messageForm.manualRecipients = ''; // 确保初始化为空字符串
        this.manualRecipientCount = 0;

        // 聚焦到手动输入框
        this.$nextTick(() => {
          if (this.$refs.manualInput) {
            setTimeout(() => {
              this.$refs.manualInput.focus();
            }, 200);
          }
        });
      }

      // 触发表单验证
      this.$nextTick(() => {
        this.$refs.messageForm?.validateField('recipientType');
      });
    },

    // 处理分组变更
    handleGroupChange(groupId) {
      console.log('选择分组:', groupId);
      // 这个方法现在由handleGroupSelect替代
    },

    // 处理文件变更
    handleFileChange(file) {
      this.fileList = [file];

      // 自动解析文件
      if (file && file.raw) {
        this.parsePhoneFile();
      }
    },

    // 处理文件移除
    handleFileRemove() {
      this.fileList = [];
      this.uploadedPhones = [];
    },

    // 处理文件上传
    handleFileUpload(options) {
      console.log('上传文件:', options.file);
      // 文件已经在handleFileChange中处理，这里不需要额外操作
      options.onSuccess(); // 通知上传组件上传成功
    },

    // 解析手机号文件
    parsePhoneFile() {
      if (this.fileList.length === 0) {
        return;
      }

      // 显示解析中提示
      const loading = this.$loading({
        lock: true,
        text: '正在解析文件...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      const file = this.fileList[0].raw;
      if (file) {
        try {
          const reader = new FileReader();

          reader.onload = (e) => {
            try {
              // 使用 xlsx 库解析 Excel 文件
              const data = new Uint8Array(e.target.result);
              const workbook = XLSX.read(data, { type: 'array' });

              // 读取第一个工作表
              const firstSheetName = workbook.SheetNames[0];
              const worksheet = workbook.Sheets[firstSheetName];

              // 将工作表转换为JSON
              const rows = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

              if (rows.length > 1) {
                const headers = rows[0]; // 第一行作为表头
                console.log("表头行:", headers);

                // 获取变量列（除了手机号以外的列）
                const variableHeaders = headers.slice(1);

                // 存储有效的联系人
                const contacts = [];

                // 从第二行开始处理数据行
                for (let i = 1; i < rows.length; i++) {
                  const row = rows[i];
                  if (row && row.length > 0) {
                    const phone = String(row[0]).trim(); // 转为字符串并移除空格
                    console.log(`处理行 ${i}，手机号: ${phone}`);

                    // 验证手机号格式
                    const phoneRegex = /^1[3-9]\d{9}$/;
                    if (phoneRegex.test(phone)) {
                      // 处理变量
                      const variable1 = String(row[1]).trim()==="undefined"?"":String(row[1]).trim();
                      const variable2 = String(row[2]).trim()==="undefined"?"":String(row[2]).trim();
                      const variable3 = String(row[3]).trim()==="undefined"?"":String(row[3]).trim();
                      const variable4 = String(row[4]).trim()==="undefined"?"":String(row[4]).trim();

                      contacts.push({
                        phone,
                        variable1,
                        variable2,
                        variable3,
                        variable4,
                      });
                    } else {
                      console.log(`行 ${i} 的手机号 ${phone} 格式无效`);
                    }
                  }
                }

                this.uploadedPhones = contacts;

                loading.close();
                if (this.uploadedPhones.length > 0) {
                  this.$message.success(`成功解析 ${this.uploadedPhones.length} 个联系人`);

                  // 如果没有设置任务名称，则自动生成
                  if (!this.messageForm.taskName) {
                    const date = new Date();
                    const dateStr = `${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}${String(date.getDate()).padStart(2, '0')}`;
                    this.messageForm.taskName = `${dateStr}_群发任务`;
                  }

                  // 触发表单验证
                  this.$nextTick(() => {
                    this.$refs.messageForm?.validateField('recipientType');
                  });
                } else {
                  this.$message.warning('未解析到有效的手机号码，请检查文件格式');
                }
              } else {
                loading.close();
                this.$message.warning('文件内容为空或格式不正确');
              }
            } catch (error) {
              console.error('解析Excel出错:', error);
              loading.close();
              this.$message.error('解析Excel文件出错，请检查文件格式');
            }
          };

          reader.onerror = () => {
            loading.close();
            this.$message.error('读取文件失败');
          };

          // 以二进制格式读取文件
          reader.readAsArrayBuffer(file);
        } catch (error) {
          console.error('文件处理错误:', error);
          loading.close();
          this.$message.error('文件处理错误，请稍后再试');
        }
      } else {
        loading.close();
        this.$message.warning('无法读取文件');
      }
    },

    // 验证手动输入的接收人
    validateManualRecipients() {
      console.log("手动输入的文本:", this.messageForm.manualRecipients);

      if (!this.messageForm.manualRecipients) {
        this.manualRecipientCount = 0;
        this.uploadedPhones = [];
        return;
      }

      // 分割并验证手机号
      const phoneRegex = /^1[3-9]\d{9}$/;
      const phones = this.messageForm.manualRecipients.split(/[,\s\n]+/).filter(phone => phone.trim() !== '');
      console.log("分割后的手机号:", phones);

      const validPhones = phones.filter(phone => phoneRegex.test(phone.trim()));
      console.log("有效的手机号:", validPhones);

      this.manualRecipientCount = validPhones.length;

      // 将手动输入的手机号转为联系人对象
      this.uploadedPhones = validPhones.map(phone => ({
        phone: phone.trim(),
        variable1: '',
        variable2: '',
        variable3: '',
        variable4: '',
        editing: false
      }));

      // 触发表单验证
      this.$nextTick(() => {
        this.$refs.messageForm?.validateField('recipientType');
      });
    },
    // 表格样式
    tableHeaderStyle() {
      return {
        background: '#f5f7fa',
        color: '#606266',
        fontWeight: 500,
        height: '50px'
      }
    },
    // 处理定时发送变更
    handleScheduleChange(val) {
      if (val && !this.messageForm.scheduledTime) {
        // 默认设置为明天此时
        const tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);

        const year = tomorrow.getFullYear();
        const month = (tomorrow.getMonth() + 1).toString().padStart(2, '0');
        const day = tomorrow.getDate().toString().padStart(2, '0');
        const hours = tomorrow.getHours().toString().padStart(2, '0');
        const minutes = tomorrow.getMinutes().toString().padStart(2, '0');

        this.messageForm.scheduledTime = `${year}-${month}-${day} ${hours}:${minutes}`;
      }
    },

    // 刷新预览
    refreshPreview() {
      // 触发视图更新
      this.$forceUpdate();
    },

    // 显示模板对话框
    showTemplateDialog() {
      this.templateSearchQuery = '';
      this.smartTemplateParams.pageNum = 1; // 重置分页
      this.templateDialogVisible = true;
    },

    // 添加模板
    handleAddTemplate() {
      this.templateEditMode = 'add';
      this.templateForm = {
        id: '',
        name: '',
        content: '',
        type: 'notification'
      };
      this.templateEditDialogVisible = true;
    },

    // 使用模板
    handleUseTemplate(template) {
      console.log(template)
      this.messageForm.templateId = template.templateId;
      this.messageForm.templateName = template.templateName;
      this.messageForm.templateContent = template.templateContent;
      if (template.templateType==='4')
      {
        this.messageForm.templateType ='3'
      }else
      {
        this.messageForm.templateType = String(template.templateType);
      }
      if(template.signatureName!==null )
      {
        this.messageForm.signatureName = template.signatureName;
      }
      if(template.signatureId!==null )
      {
        this.messageForm.signatureId = template.signatureId;
      }

      // 生成任务名称
      const date = new Date();
      const dateStr = `${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}${String(date.getDate()).padStart(2, '0')}`;
      this.messageForm.taskName = `${dateStr}_${template.templateName}`;

      this.updateCharCount();
      this.templateDialogVisible = false;
    },

    // 发送消息
    handleSendMessage() {
      if (!this.canSend) {
        return;
      }

      this.$refs.messageForm.validate((valid) => {
        if (valid) {
          this.sendConfirmDialogVisible = true;
        }
      });
    },

    // 确认发送消息
    confirmSendMessage() {
      // 显示加载中
      const loading = this.$loading({
        lock: true,
        text: '正在处理...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });


      try {
        // 1. 准备收件人数据
        let recipients = [];

        if (this.messageForm.recipientType === 'upload' || this.messageForm.recipientType === 'manual') {
          // 处理上传或手动输入的联系人
          recipients = this.uploadedPhones.map(contact => {
            return {
              phoneNumber: contact.phone,
              variable1: contact.variable1,
              variable2: contact.variable2,
              variable3: contact.variable3,
              variable4: contact.variable4,
              status: '0' // 状态：0=未发送，1=已发送，2=发送失败
            };
          });
        } else if (this.messageForm.recipientType === 'group') {
          // 处理分组联系人
          if (this.selectedContacts && this.selectedContacts.length > 0) {
            recipients = this.selectedContacts.map(customer => {
              return {
                phoneNumber: customer.phoneNumber,
                variable1: customer.customerName || '',
                variable2: customer.email || '',
                variable3: customer.remark || '',
                variable4: '',
                status: '0'
              };
            });
          } else {
            loading.close();
            this.$message.warning('请先选择联系人');
            return;
          }
        }

        // 验证收件人数据
        if (recipients.length === 0) {
          loading.close();
          this.$message.warning('没有有效的收件人，请检查数据');
          return;
        }

        // 2. 准备任务数据
        const taskData = {
          taskId: this.messageForm.taskId,
          taskName: this.messageForm.taskName || `${new Date().toISOString().slice(0, 10)}_发送任务`,
          templateId: this.messageForm.templateId,
          templateType: this.messageForm.templateType,
          signatureId: this.messageForm.signatureId,
          templateContent: this.messageForm.templateContent,
          smsContent: this.messageForm.templateContent,
          scheduledTime: this.messageForm.scheduledTime,
          taskStatus: '1', // 状态：0=草稿，1=待发送，2=发送中，3=已发送，4=发送失败
          recipientCount: this.recipientCount,
          messageCount: this.totalMessageCount,
          estimatedCost: this.estimatedCost,
          remark: this.messageForm.recipientType === 'group' ? '联系人群发' : '',
          userId: this.$store.state.user.userId,
          recipients: recipients
        };
        console.log("短信任务：");
        console.log(taskData);
        if (taskData.taskId != null) {
          updateBulkTask(taskData).then(response => {
            if (response.code === 200) {
              loading.close();
              this.$message.success('提交成功');
              this.getHistorySmsTask();
            } else {
              loading.close();
              this.$message.error('提交失败: ' + response.msg);
            }

          }).catch(error => {
          console.error('提交过程出错', error);
          loading.close();
          this.$message.error('提交出错，请稍后再试');
        });
        } else {
          // 2. 保存任务基本信息
          addBulkTask(taskData).then(response => {
            if (response.code === 200) {

              loading.close();

              this.$message.success('任务提交成功');
              //this.resetForm(); // 重置表单
              this.getHistorySmsTask();

            } else {
              loading.close();
              this.$message.error('任务提交失败: ' + response.msg);
            }
          }).catch(error => {
            console.error('任务提交出错', error);
            loading.close();
            this.$message.error('任务提交出错，请稍后再试');
          });
        }
      } catch (error) {
        console.error('任务提交出错', error);
        loading.close();
        this.$message.error('任务提交出错，请稍后再试');
      }

      this.sendConfirmDialogVisible = false;
    },

    // 重置表单
    resetForm() {
      this.messageForm = {
        taskId: null,
        templateType: '1',
        signatureId: '',
        signatureName: '',
        templateId: '',
        templateName: '',
        templateContent: '',
        taskName: '',
        recipientType: 'group',
        manualRecipients: '',
        scheduledTime: ''
      };

      this.fileList = [];
      this.uploadedPhones = [];
      this.selectedContacts = [];
      this.manualRecipientCount = 0;
      this.charCount = 0;
      this.messageCount = 1;
      this.currentPage = 1;

      // 清除验证
      if (this.$refs.messageForm) {
        this.$refs.messageForm.clearValidate();
      }
    },

    // 查看发送历史详情
    viewHistoryDetail(history) {
      this.$message({
        message: `查看发送记录: ${history.title}`,
        type: 'info'
      });
    },

    // 查看全部发送历史
    viewAllHistory() {
      this.$router.push({
        name: 'SmsHistory'
      });
    },

    // 获取模板类型标签样式
    getTemplateTypeTag(type) {
      const types = {
        'notification': 'success',
        'marketing': 'warning',
        'verification': 'primary'
      };
      return types[type] || '';
    },

    // 获取模板类型名称
    getTemplateTypeName(type) {
      const types = {
        'notification': '通知',
        'marketing': '营销',
        'verification': '验证码'
      };
      return types[type] || '未知';
    },

    // 下载手机号模板
    downloadPhoneTemplate(e) {
      e && e.stopPropagation();

      try {
        // 创建工作簿
        const wb = XLSX.utils.book_new();

        // 创建工作表数据
        const data = [
          ['手机号码', '变量1', '变量2', '变量3'],
          ['18888888888', '值1', '值2', '值3'],
          ['13999999999', '测试1', '测试2', '测试3']
        ];

        // 将数据转换为工作表
        const ws = XLSX.utils.aoa_to_sheet(data);

        // 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(wb, ws, '联系人模板');

        // 将工作簿写入文件并触发下载
        XLSX.writeFile(wb, '手机号码导入模板.xlsx');

        this.$message({
          message: "模板下载成功",
          type: "success"
        });
      } catch (error) {
        console.error('导出Excel出错:', error);
        this.$message.error('导出Excel出错，请稍后再试');
      }
    },



    // 处理联系人选择
    handleContactSelectionChange(selectedContacts) {
      this.selectedContacts = selectedContacts;
    },

    // 添加新联系人
    addNewContact() {
      this.uploadedPhones.push({
        phone: '',
        variable1: '',
        variable2: '',
        variable3: '',
        variable4: '',
        editing: true
      });
    },

    // 编辑联系人
    editContact(contact) {
      contact.editing = true;
    },

    // 保存联系人
    saveContact(contact) {
      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(contact.phone)) {
        this.$message.error('请输入有效的手机号码');
        return;
      }

      // 将编辑状态设为false
      contact.editing = false;

      // 更新uploadedPhones数组中的联系人数据
      const index = this.uploadedPhones.findIndex(item => item === contact);
      if (index !== -1) {
        this.uploadedPhones[index] = {
          ...contact,
          phone: contact.phone.trim(),
          variable1: contact.variable1 || '',
          variable2: contact.variable2 || '',
          variable3: contact.variable3 || '',
          variable4: contact.variable4 || ''
        };
      }

      this.$message.success('联系人信息已保存');
    },

    // 取消编辑
    cancelEdit(contact, index) {
      contact.editing = false;
    },

    // 删除联系人
    deleteContact(index) {
      const filteredIndex = this.filteredContacts[index];
      const realIndex = this.uploadedPhones.findIndex(contact => contact === filteredIndex);
      if (realIndex !== -1) {
        this.uploadedPhones.splice(realIndex, 1);
      }
    },

    // 处理联系人搜索
    handleSizeChange(newSize) {
      this.pageSize = newSize;
    },

    // 处理联系人当前页变更
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },

    // 处理联系人变量操作
    handleVariableChange(contact, key, value) {
      if (value) {
        contact.variables = { ...contact.variables, [key]: value };
      } else {
        delete contact.variables[key];
      }
    },

    // 删除选中的联系人
    deleteSelectedContacts() {
      this.$confirm('确定要删除选中的联系人吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 获取选中联系人的索引
        const selectedIds = this.selectedContacts.map(contact =>
          this.uploadedPhones.findIndex(item => item === contact)
        ).filter(index => index !== -1);

        // 从高到低排序索引，这样删除时不会影响其他元素的索引
        selectedIds.sort((a, b) => b - a);

        // 逐个删除选中的联系人
        selectedIds.forEach(index => {
          this.uploadedPhones.splice(index, 1);
        });

        this.selectedContacts = [];

        this.$message({
          message: '成功删除选中的联系人',
          type: 'success'
        });
      }).catch(() => {});
    },

    // 处理暂存任务
    handleSaveDraft() {
      if (!this.canSaveDraft) {
        return;
      }

      // 显示加载中
      const loading = this.$loading({
        lock: true,
        text: '正在保存任务...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      try {
        // 1. 准备收件人数据
        let recipients = [];

        if (this.messageForm.recipientType === 'upload' || this.messageForm.recipientType === 'manual') {
          // 处理上传或手动输入的联系人
          recipients = this.uploadedPhones.map(contact => {
            return {
              phoneNumber: contact.phone,
              variable1: contact.variable1,
              variable2: contact.variable2,
              variable3: contact.variable3,
              variable4: contact.variable4,
              status: '0' // 状态：0=未发送，1=已发送，2=发送失败
            };
          });
        } else if (this.messageForm.recipientType === 'group') {
          // 处理分组联系人
          if (this.selectedContacts && this.selectedContacts.length > 0) {
            recipients = this.selectedContacts.map(customer => {
              return {
                phoneNumber: customer.phoneNumber,
                variable1: customer.customerName || '',
                variable2: customer.email || '',
                variable3: customer.remark || '',
                variable4: '',
                status: '0'
              };
            });
          } else {
            loading.close();
            this.$message.warning('请先选择联系人');
            return;
          }
        }

        // 验证收件人数据
        if (recipients.length === 0) {
          loading.close();
          this.$message.warning('没有有效的收件人，请检查数据');
          return;
        }

        // 2. 准备任务数据
        const taskData = {
          taskId: this.messageForm.taskId,
          taskName: this.messageForm.taskName || `${new Date().toISOString().slice(0, 10)}_草稿任务`,
          templateId: this.messageForm.templateId,
          templateType: this.messageForm.templateType,
          signatureId: this.messageForm.signatureId,
          templateContent: this.messageForm.templateContent,
          smsContent: this.messageForm.templateContent,
          scheduledTime: this.messageForm.scheduledTime,
          taskStatus: '0', // 状态：0=草稿，1=待发送，2=发送中，3=已发送，4=发送失败
          recipientCount: this.recipientCount,
          messageCount: this.totalMessageCount,
          estimatedCost: this.estimatedCost,
          remark: this.messageForm.recipientType === 'group' ? '联系人群发暂存' : '通过群发页面暂存',
          userId: this.$store.state.user.userId,
          recipients: recipients
        };
        console.log("短信任务：");
        console.log(taskData);
        if (taskData.taskId != null) {
          updateBulkTask(taskData).then(response => {
            if (response.code === 200) {
              loading.close();
              this.$message.success('修改成功');
              this.getHistorySmsTask();
            } else {
              loading.close();
              this.$message.error('修改失败: ' + response.msg);
            }

          }).catch(error => {
          console.error('修改过程出错', error);
          loading.close();
          this.$message.error('修改出错，请稍后再试');
        });
        } else {
          // 2. 保存任务基本信息
          addBulkTask(taskData).then(response => {
            if (response.code === 200) {

              loading.close();

              this.$message.success('任务暂存成功');
              //this.resetForm(); // 重置表单
              this.getHistorySmsTask();

            } else {
              loading.close();
              this.$message.error('保存任务失败: ' + response.msg);
            }
          }).catch(error => {
            console.error('保存过程出错', error);
            loading.close();
            this.$message.error('保存过程出错，请稍后再试');
          });
        }
      } catch (error) {
        console.error('保存过程出错', error);
        loading.close();
        this.$message.error('保存过程出错，请稍后再试');
      }
    },

    // 处理暂存任务完成后导航到任务列表
    navigateToTaskList() {
      // 导航到任务列表页面
      this.$router.push({
        path: '/smstask/smstask'
      });
    },

    // 文件上传前的验证
    beforeExcelUpload(file) {
      const isExcel =
        file.type === 'application/vnd.ms-excel' ||
        file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.name.endsWith('.xls') ||
        file.name.endsWith('.xlsx');

      const isLt50M = file.size / 1024 / 1024 < 50;

      if (!isExcel) {
        this.$message.error('只能上传Excel文件!');
      }

      if (!isLt50M) {
        this.$message.error('文件大小不能超过 50MB!');
      }

      return isExcel && isLt50M;
    },

    getTaskStatusType(status) {
      const statusTypes = {
        '0': 'info',    // 草稿
        '1': 'warning', // 待发送
        '2': 'primary', // 发送中
        '3': 'success', // 已完成
        '4': 'danger'   // 已取消
      };
      return statusTypes[status] || 'info';
    },

    getTaskStatusText(status) {
      const statusTexts = {
        '0': '草稿',
        '1': '待发送',
        '2': '发送中',
        '3': '已完成',
        '4': '已取消'
      };
      return statusTexts[status] || '未知';
    },

    // 加载任务数据
    loadTaskData(task) {
      this.resetForm(); // 重置表单
      // 显示加载中
      const loading = this.$loading({
        lock: true,
        text: '正在加载任务数据...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      // 调用API获取任务详情
      getBulkTask(task.taskId).then(response => {
        if (response.code === 200) {
          const taskData = response.data;

          // 填充消息内容
          this.messageForm.taskId = taskData.taskId;
          this.messageForm.taskName = taskData.taskName;
          this.messageForm.templateId = taskData.templateId;
          this.messageForm.templateType = String(taskData.templateType);
          this.messageForm.signatureId = taskData.signatureId;
          this.messageForm.templateContent = taskData.smsContent;

          // 处理签名
          const signature = this.signatures.find(sig => sig.signatureId === taskData.signatureId);
          if (signature) {
            this.messageForm.signatureName = signature.signatureName;
          }

          // 处理模板
          const template = this.templates.find(t => t.templateId === taskData.templateId);
          if (template) {
            this.messageForm.templateName = template.templateName;
          }

          // 设置为上传模式
          this.messageForm.recipientType = 'upload';

          // 加载收件人列表
          if (taskData.recipients && taskData.recipients.length > 0) {
            this.uploadedPhones = taskData.recipients.map(recipient => ({
              phone: recipient.phoneNumber,
              variable1: recipient.variable1 || '',
              variable2: recipient.variable2 || '',
              variable3: recipient.variable3 || '',
              variable4: recipient.variable4 || '',
              editing: false
            }));
          }

          // 处理定时发送
          if (taskData.scheduledTime) {
            this.messageForm.scheduledSend = true;
            this.messageForm.scheduledTime = taskData.scheduledTime;
          } else {
            this.messageForm.scheduledSend = false;
            this.messageForm.scheduledTime = '';
          }

          // 更新预览和统计
          this.updateCharCount();
          this.refreshPreview();

          // 滚动到页面顶部
          window.scrollTo(0, 0);

          this.$message.success('任务数据加载成功');
        } else {
          this.$message.error('加载任务数据失败: ' + response.msg);
        }
        loading.close();
      }).catch(error => {
        console.error('加载任务数据失败', error);
        this.$message.error('加载任务数据失败，请稍后再试');
        loading.close();
      });
    },

    // 处理智能模版分页变化
    handleSmartTemplatePageChange(page) {
      this.smartTemplateParams.pageNum = page;
    },

    // 获取模版对话框标题
    getTemplateDialogTitle() {
      const typeNames = {
        '1': '通知消息',
        '2': '营销消息',
        '3': '智能消息'
      };
      const typeName = typeNames[this.messageForm.templateType] || '消息';
      return `选择${typeName}模版`;
    },

    // 获取空状态消息
    getEmptyStateMessage() {
      const typeNames = {
        '1': '通知消息',
        '2': '营销消息',
        '3': '智能消息'
      };
      const typeName = typeNames[this.messageForm.templateType] || '消息';

      if (this.templateSearchQuery) {
        return `未找到匹配的${typeName}模版`;
      } else {
        return `暂无${typeName}模版`;
      }
    },

    // 设置默认定时发送时间
    setDefaultScheduledTime() {
      const now = new Date();
      now.setMinutes(now.getMinutes() + 2); // 当前时间后2分钟

      const year = now.getFullYear();
      const month = (now.getMonth() + 1).toString().padStart(2, '0');
      const day = now.getDate().toString().padStart(2, '0');
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');

      this.messageForm.scheduledTime = `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    // 联系人选择相关方法
    getContactGroupTree() {
      listContactGroup({}).then(response => {
        const groups = response.data || [];
        const tree = this.handleTree(groups, 'groupId', 'parentId');
        this.contactGroupTreeData = [{ groupId: 0, groupName: '全部联系人', children: tree }];
      });
    },
    showContactDialog() {
      console.log('SMS showContactDialog 被调用，当前selectedContacts:', this.selectedContacts);
      this.contactDialogVisible = true;
      this.getContactList();
    },
    handleContactGroupClick(data) {
      if (data.groupId === 0) {
        this.currentContactGroupId = null;
        this.currentContactGroupName = '全部联系人';
      } else {
        this.currentContactGroupId = data.groupId;
        this.currentContactGroupName = data.groupName;
      }
      this.contactQueryParams.groupId = this.currentContactGroupId;
      this.contactQueryParams.pageNum = 1;
      this.getContactList();
    },
    getContactList() {
      this.contactLoading = true;
      listContactCustomer(this.contactQueryParams).then(response => {
        this.contactList = response.rows;
        this.contactTotal = response.total;
        this.contactLoading = false;
        
        // 数据加载完成后，延迟恢复已选择的联系人状态
        setTimeout(() => {
          this.restoreContactSelection();
        }, 100);
      });
    },
    handleContactSelectionChange(selection) {
      console.log('SMS handleContactSelectionChange 被调用，当前选择:', selection);
      console.log('SMS 之前的selectedContacts:', this.selectedContacts);
      
      // 获取当前页面的联系人ID列表
      const currentPageContactIds = this.contactList.map(contact => contact.customerId);
      console.log('SMS 当前页面联系人ID:', currentPageContactIds);
      
      // 保留不在当前页面的已选择联系人
      const contactsNotInCurrentPage = this.selectedContacts.filter(contact => 
        !currentPageContactIds.includes(contact.customerId)
      );
      console.log('SMS 不在当前页面的已选联系人:', contactsNotInCurrentPage);
      
      // 合并当前页面的选择和其他页面的选择
      this.selectedContacts = [...contactsNotInCurrentPage, ...selection];
      console.log('SMS 合并后的selectedContacts:', this.selectedContacts);
    },
    
    // 恢复联系人选择状态
    restoreContactSelection() {
      console.log('SMS restoreContactSelection 被调用');
      console.log('SMS 当前selectedContacts:', this.selectedContacts);
      console.log('SMS 当前contactList:', this.contactList);
      console.log('SMS contactTable ref:', this.$refs.contactTable);
      
      if (!this.$refs.contactTable) {
        console.log('SMS 表格引用不存在，跳过恢复');
        return;
      }
      
      if (this.selectedContacts.length === 0) {
        console.log('SMS 没有已选择的联系人，跳过恢复');
        return;
      }

      // 先清除当前表格选择，防止冲突
      this.$refs.contactTable.clearSelection();

      // 使用 $nextTick 确保表格已经渲染
      this.$nextTick(() => {
        // 根据已选择的联系人ID来恢复表格选择状态
        this.contactList.forEach(contact => {
          const isSelected = this.selectedContacts.some(selected => 
            selected.customerId === contact.customerId
          );
          console.log(`SMS 联系人 ${contact.customerName} (ID: ${contact.customerId}) 是否已选择:`, isSelected);
          if (isSelected) {
            this.$refs.contactTable.toggleRowSelection(contact, true);
          }
        });
        console.log('SMS 恢复选择状态完成');
      });
    },
    confirmContactSelection() {
      this.contactDialogVisible = false;
      this.$message.success(`已选择 ${this.selectedContacts.length} 个联系人`);
      
      // 触发表单验证
      this.$nextTick(() => {
        this.$refs.messageForm.validateField('recipientType');
      });
    },

    // 验证接收人
    validateRecipients(rule, value, callback) {
      console.log("验证接收人 - recipientType:", this.messageForm.recipientType);
      console.log("验证接收人 - selectedContacts.length:", this.selectedContacts.length);

      if (this.messageForm.recipientType === 'group') {
        // 检查是否选择了联系人
        if (this.selectedContacts.length === 0) {
          callback(new Error('请选择接收人'));
          return;
        }
        callback();
      } else if (this.messageForm.recipientType === 'upload') {
        if (this.uploadedPhones.length === 0) {
          callback(new Error('请导入接收人号码'));
        } else {
          callback();
        }
      } else if (this.messageForm.recipientType === 'manual') {
        if (this.manualRecipientCount === 0) {
          callback(new Error('请输入有效的接收人号码'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
  },
  mounted() {
    // 初始化字符计数
    this.updateCharCount();

    // 默认选择第一个签名
    if (this.signatures.length > 0) {
      this.messageForm.signatureName = this.signatures[0].signatureName;
    }
  }
}
</script>

<style scoped>
.sms-mass-messaging-container {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

/* 页面标题样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-title {
  font-size: 22px;
  color: #303133;
  margin: 0;
}

.version-tag {
  font-size: 12px;
  height: 22px;
  line-height: 20px;
  padding: 0 8px;
}

.header-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin: 20px 0;
}

.header-actions .el-button {
  min-width: 120px;
  padding: 10px 20px;
  font-size: 14px;
}

/* 信息提示条样式 */
.info-alert {
  margin-bottom: 20px;
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-title i {
  font-size: 18px;
  color: #409eff;
}

/* 消息编辑器卡片样式 */
.message-editor-card {
  margin-bottom: 20px;
}

/* 模板选择器样式 */
.template-selector {
  display: flex;
  align-items: center;
  gap: 10px;
}

.template-option {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.template-name {
  font-weight: 500;
}

.template-content {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 内容底部样式 */
.content-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.variable-buttons {
  display: flex;
  gap: 8px;
}

.char-counter {
  font-size: 12px;
  color: #606266;
}

.char-counter.warning {
  color: #e6a23c;
}

.message-count {
  margin-left: 4px;
  color: #409eff;
}

/* 接收人选择器样式 */
.recipient-group-selector,
.recipient-upload,
.recipient-manual {
  margin-top: 12px;
}

/* 分组信息显示样式 */
.group-info-display {
  margin-top: 15px;
}

.group-info-display .el-alert {
  border-radius: 6px;
}

.group-info-display .el-alert p {
  margin: 5px 0;
  font-size: 14px;
}

.group-info-display .el-alert p:last-child {
  margin-bottom: 0;
}



/* 定时发送选择器样式 */
.schedule-selector {
  margin-top: 12px;
}

/* 预览卡片样式 */
.preview-card {
  margin-bottom: 20px;
}

.phone-preview {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.phone-frame {
  width: 280px;
  height: 500px;
  border: 10px solid #303133;
  border-radius: 30px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background-color: #f0f0f0;
}

.phone-header {
  height: 50px;
  background-color: #303133;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}

.phone-content {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
}

.message-bubble {
  background-color: #fff;
  border-radius: 10px;
  padding: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-sender {
  font-weight: 500;
  margin-bottom: 8px;
  color: #409eff;
}

.message-content {
  line-height: 1.5;
  word-break: break-all;
}

.message-time {
  text-align: right;
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

/* 统计卡片样式 */
.stats-card {
  margin-bottom: 20px;
}

.stats-content {
  padding: 10px 0;
}

.stats-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.stats-item:last-child {
  border-bottom: none;
}

.stats-label {
  color: #606266;
}

.stats-value {
  font-weight: 500;
  color: #303133;
}

.stats-value.highlight {
  color: #f56c6c;
  font-size: 18px;
}

.stats-value.price {
  color: #409eff;
  font-weight: 600;
}

.stats-value.price.highlight {
  color: #f56c6c;
  font-size: 18px;
}

.send-button-container {
  margin-top: 20px;
}

/* 历史记录卡片样式 */
.history-card {
  margin-bottom: 20px;
}

.history-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.history-title {
  font-weight: 500;
  color: #303133;
}

.history-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

/* 模板对话框样式 */
.template-dialog-content {
  max-height: 500px;
  overflow-y: auto;
}

.template-actions {
  display: flex;
  margin-bottom: 16px;
}

.template-tips {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  background-color: #f5f7fa;
  padding: 8px;
  border-radius: 4px;
}

.template-tips p {
  margin: 4px 0;
}

/* 发送确认对话框样式 */
.send-confirm-content {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.confirm-icon {
  font-size: 48px;
  color: #e6a23c;
}

.confirm-info {
  flex: 1;
}

.confirm-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 16px;
}

.confirm-detail {
  margin: 8px 0;
  color: #606266;
}

/* 响应式样式 */
@media screen and (max-width: 1200px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}

@media screen and (max-width: 768px) {
  .sms-mass-messaging-container {
    padding: 10px;
  }

  .template-selector {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .template-selector .el-select {
    width: 100% !important;
  }

  .content-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .header-actions {
    flex-direction: column;
  }

  .header-actions .el-button {
    width: 100%;
  }

  .phone-frame {
    width: 240px;
    height: 400px;
  }
}

/* 上传提示样式增强 */
.el-upload__tip {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 8px;
}

.el-upload__tip .el-button {
  margin-left: 8px;
}

/* 联系人预览样式 */
.contacts-preview {
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 0;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.contacts-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 0;
}

.contact-count {
  font-weight: 500;
  color: #303133;
}

.contacts-actions {
  display: flex;
  gap: 8px;
}

.contacts-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0;
  padding: 15px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
}

.left-tools {
  display: flex;
  gap: 10px;
}

.right-tools {
  display: flex;
  gap: 15px;
  align-items: center;
}

.variable-edit-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.variable-input-group {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.variable-key {
  margin-right: 8px;
  min-width: 60px;
  font-weight: 500;
}

.add-variable-row {
  display: flex;
  align-items: center;
  margin-top: 5px;
  gap: 8px;
}

.variable-display {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.variable-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.no-variables {
  color: #909399;
  font-size: 12px;
}

.pagination-container {
  margin-top: 5;
  padding: 20px;
  text-align: center;
  background-color: #f5f7fa;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: center;
  align-items: center;
}

.pagination-container .el-pagination {
  padding: 0;
  font-weight: normal;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination-container .el-pagination .el-pager {
  display: flex;
  margin: 0 15px;
}

.pagination-container .el-pagination button {
  min-width: 40px;
  height: 40px;
  padding: 0;
  margin: 0 5px;
  border-radius: 4px;
}

.contacts-preview .el-table {
  margin: 0;
  border-radius: 0;
}

/* Prevent horizontal scrolling by keeping the table fixed */
.contacts-preview .el-table__body-wrapper {
  overflow-x: hidden;
}

/* Better row highlighting */
.contacts-preview .el-table__row:hover {
  background-color: #f0f7ff !important;
}

/* Style the table header */
.contacts-preview .el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
  padding: 12px 0;
}

/* Add more space between page numbers */
.pagination-container .el-pagination .el-pager li {
  margin: 0 5px;
  min-width: 32px;
}

/* Make the active page number more visible */
.pagination-container .el-pagination .el-pager li.active {
  font-weight: bold;
  color: #fff;
  background-color: #409eff;
  border-radius: 4px;
}

.pagination-container .el-pagination .el-select .el-input {
  margin: 0 5px;
}

.pagination-container .el-pagination .el-pagination__total {
  margin-right: 10px;
}

.pagination-container .el-pagination .el-pagination__sizes {
  margin: 0 10px;
}

.pagination-container .el-pagination .el-pagination__jump {
  margin-left: 10px;
}

/* 添加到 style 部分 */
.manual-error-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #f56c6c;
}

.manual-recipient-counter {
  margin-top: 8px;
  font-size: 12px;
  color: #606266;
  display: flex;
  align-items: center;
}

.recipient-manual {
  margin-top: 12px;
  width: 100%;
}

.recipient-manual .el-textarea {
  width: 100%;
}

.price {
  font-weight: bold;
  color: #f56c6c;
}

.highlight {
  color: #409eff;
  font-weight: 500;
}

/* 智能模版对话框样式 */
.smart-template-dialog .el-dialog {
  min-height: 600px;
}

.smart-templates-container {
  min-height: 400px;
}

.template-cards {

  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(242px, 1fr));
  gap: 10px;
  margin-top: 10px;
}

.template-card {
  width: 242px;
  height: 310px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
  transition: all 0.3s;
  cursor: pointer;
  position: relative;
}

.template-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.card-status {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 10;
}

.card-image {
  height: 120px;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.no-image {
  color: #c0c4cc;
  font-size: 32px;
}

.card-info {
  padding: 15px;
}

.card-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-description {
  margin: 0 0 10px 0;
  font-size: 12px;
  color: #606266;
  line-height: 1.4;
  height: 32px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.card-meta {
  font-size: 12px;
  color: #909399;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.card-footer {
  padding: 0 15px 15px 15px;
  text-align: center;
}

.template-pagination {
  margin-top: 20px;
  text-align: center;
}

.normal-templates-container {
  margin-top: 20px;
}

.empty-state {
  text-align: center;
  color: #909399;
  font-size: 14px;
  margin-top: 20px;
  padding: 40px 20px;
}

.empty-state i {
  display: block;
  margin-bottom: 10px;
  font-size: 48px;
  color: #c0c4cc;
}

/* 联系人选择相关样式 */
.selected-contacts-preview {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.more-contacts {
  color: #909399;
  font-size: 12px;
  margin-left: 5px;
}

/* 统一的el-tree样式 */
.group-tree-card .el-tree {
  background-color: transparent;
}

.group-tree-card .el-tree-node {
  margin-bottom: 4px;
}

.group-tree-card >>> .el-tree-node__content {
  height: 36px !important;
  line-height: 36px !important;
  min-height: 36px !important;
  padding: 0 10px 0 0 !important;
}

.group-tree-card .el-tree-node__expand-icon {
  padding: 6px;
}

.group-tree-card .el-tree-node__label {
  font-size: 14px;
}

.group-tree-card .el-card__body {
  padding: 20px;
}

.contact-list-card .el-card__body {
  padding: 20px;
}

.custom-tree-node {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 0px;
  font-size: 14px;
  height: 36px;
  line-height: 36px;
}

.node-label {
  display: flex;
  align-items: center;
}

.tree-icon {
  margin-right: 8px;
  font-size: 16px;
}
</style>
